import { createStore } from 'vuex'
import axios from '@/services/api'

const store = createStore({
  state() {
    return {
      token: localStorage.getItem('token') || '',
      
      permissions: JSON.parse(localStorage.getItem('permissions')) || []
    }
  },
  mutations: {
    setToken(state, token) {
      state.token = token
      localStorage.setItem('token', token)
    },
    clearToken(state) {
      state.token = ''
      localStorage.removeItem('token')
    },
    setPermissions(state, permissions) {
      state.permissions = permissions
      localStorage.setItem('permissions', JSON.stringify(permissions))
    }
  },
  actions: {
    login({ commit }, token) {
      commit('setToken', token)
    },
    logout({ commit }) {
      commit('clearToken')
    },
    async fetchPermissions({ commit }) {
      const response = await axios.get('/system/user/findResourcesEMUByResources')
      var s = new Array()
          for (var i = 0; i < response.data.data.length; i++) {
            s.push(response.data.data[i].url)
          }
      commit('setPermissions', s)
    }
  }
})

export default store